<route lang="json5">
{
  style: {
    navigationBarTitleText: '干部入驻',
  },
}
</route>
<template>
  <view class="bg-#F6F6F6 overflow-auto w-100% h-screen box-border">
    <view class="w-100% h-300rpx position-relative">
      <img class="login_bg pos-absolute" src="../../static/images/loginBg1.png" />
      <view class="login_title">请填写认证信息，提交后由管理员审批</view>
      <view>
        <wd-img-cropper
          class="z-100"
          v-model="show"
          :img-src="src"
          @confirm="handleConfirmImg"
          @cancel="handleCancel"
        ></wd-img-cropper>
        <view class="profile">
          <view v-if="!imgSrc" class="img" @click="upload">
            <img
              class="w-150rpx h-150rpx pos-absolute z-3"
              style="left: 50%; transform: translateX(-50%)"
              src="../../static/images/loginUser1.png"
            />
          </view>
          <wd-img
            v-if="imgSrc"
            round
            width="160rpx"
            height="160rpx"
            :src="imgSrc"
            mode="aspectFit"
            custom-class="profile-img"
            @click="upload"
          />
          <view style="font-size: 14px">点击上传头像</view>
        </view>
      </view>
    </view>
    <view class="imgCont"></view>

    <wd-form ref="form" :model="model" :rules="rules" class="pt-30rpx">
      <wd-cell-group
        border
        style="border-bottom-right-radius: 36rpx; border-bottom-left-radius: 36rpx"
      >
        <view @click="openTree">
          <wd-input
            label="归属区域"
            label-width="100px"
            prop="gridBelongedName"
            disabled
            suffix-icon="arrow-right"
            v-model="model.gridBelongedName"
            placeholder="请选择"
            :rules="[{ required: true, message: '请选择归属区域' }]"
          />
        </view>

        <wd-picker
          label="姓名"
          label-width="100px"
          prop="memberName"
          clearable
          v-model="model.memberName"
          placeholder="请输入真实姓名"
          :columns="userlist"
          :rules="[{ required: true, message: '请填写姓名' }]"
        />

        <wd-input
          label="联系电话"
          label-width="100px"
          prop="telephone"
          clearable
          v-model="model.telephone"
          placeholder="请输入手机号码"
          :rules="[{ required: true, message: '请填写手机号码' }]"
        />
        <wd-picker
          label="角色"
          placeholder="请选择"
          label-width="100px"
          prop="role"
          v-model="model.role"
          :columns="rolelist"
          :rules="[{ required: true, message: '请选择角色' }]"
        />
        <wd-select-picker
          label="人员身份"
          label-width="100px"
          prop="identity"
          v-model="model.identity"
          :columns="classList"
          placeholder="请选择"
          :rules="[{ required: true, message: '请选择人员身份' }]"
        />
      </wd-cell-group>
    </wd-form>
    <view class="footer pos-absolute p-20rpx overflow-auto w-100% box-border">
      <wd-button plain hairline block @click="handleSubmit">提交</wd-button>
    </view>
    <next-tree
      :selectParent="true"
      :checkStrictly="true"
      funcMode="radio"
      ref="nextTreeRef"
      :treeData="treeData"
      @confirm="treeConfirm"
    />
  </view>
</template>

<script lang="ts" setup>
import { useToast } from 'wot-design-uni'
import { getSimplePage, createGrid, getResident } from '@/service/cadre/index'
import { FormRules } from 'wot-design-uni/components/wd-form/types'
import { useUserStore } from '@/store'
import { getClassify } from '@/service/index/index'
import nextTree from '@/components/next-tree/next-tree.vue'
import { handleTree } from '@/utils/index'
const treeData = ref([])
const userStore = useUserStore()
const src = ref<string>('')
const imgSrc = ref<string>('')
const show = ref<boolean>(false)
const toast = useToast()
const form = ref()
const rules: FormRules = {
  telephone: [
    {
      required: true,
      message: '请输入正确的手机号',
      pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/,
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error('请输入手机号'))
        }
      },
    },
  ],
}

const model = reactive<{
  gridBelonged: string
  gridBelongedName: string
  memberName: string
  telephone: string
  role: string
  photo: string
  identity: []
}>({
  gridBelonged: '',
  gridBelongedName: '',
  memberName: '',
  telephone: '',
  role: '',
  identity: [],
  photo: '',
})
const userlist = ref<any[]>([
  {
    value: '1',
    label: '暂无数据',
  },
])
const classList = ref<any[]>([
  {
    value: '1',
    label: '暂无数据',
  },
])
const rolelist = ref<any[]>([
  {
    value: '1',
    label: '网格长',
  },
  {
    value: '2',
    label: '网格员',
  },
])

/**
 * @description: 头像上传
 * @return {*}
 */
function upload() {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      const tempFilePaths = res.tempFilePaths[0]
      src.value = tempFilePaths
      show.value = true
    },
  })
}
/**
 * @description: 图片上传
 * @param {*} event
 * @return {*}
 */
function handleConfirmImg(event) {
  const { tempFilePath } = event
  imgSrc.value = tempFilePath
  const uploadTask = uni.uploadFile({
    url: '/admin-api/infra/file/business/upload', // 自己文件上传的路径
    method: 'POST',
    filePath: tempFilePath,
    name: 'file',
    success: (res) => {
      const { data } = JSON.parse(res.data)
      model.photo = data.url
    },
    fail: (err) => {
      toast.error({
        msg: err + '',
      })
    },
    complete: () => {},
  })
}

function handleCancel(event) {
  console.log('取消', event)
}
function treeConfirm(info) {
  const { id, label } = info[0]
  model.gridBelonged = id
  model.gridBelongedName = label
}

function handleSubmit() {
  form.value.validate().then(({ valid, errors }) => {
    if (valid) {
      const memberName = userlist.value.filter((item) => item.id === model.memberName)[0].label
      createGrid(
        {
          ...model,
          memberName,
          gridBelongedName: undefined,
          identity: model.identity.join(','),
        },
        model.memberName,
      ).then((res) => {
        if (res && res.code === 0) {
          toast.success({
            msg: '创建成功',
          })
          setTimeout(() => {
            console.log(res.data, 9999999999)
            userStore.setGridMemberId(res.data)
            uni.switchTab({ url: '/pages/index/index' })
            toast.close()
          }, 1500)
        } else {
          toast.error({
            msg: res.msg || '注册失败',
          })
          setTimeout(() => {
            userStore.setResidentId(res.data)
            uni.reLaunch({ url: '/pages/Login/index' })
            toast.close()
          }, 1000)
        }
      })
    }
  })
}
onLoad(() => {
  getInitData()
})

async function getInitData() {
  const { data }: { data: any } = await getSimplePage()
  data.forEach((item) => {
    item.value = item.id
    item.label = item.gridName
  })
  treeData.value.push(...handleTree(data))
  const Resident: any = await getResident()
  Resident.data.forEach((item) => {
    item.value = item.id
    item.label = item.residentName
  })
  userlist.value = Resident.data
  const classData: any = await getClassify({
    pageNo: 1,
    pageSize: 100,
    dictType: 'countryside_person_identity',
  })

  classList.value = classData.data.list
}

const nextTreeRef = ref()

function changeVerify(current, chooseList) {
  // 注意：返回非空字符串会阻止原有行为，并提示返回的字符串
  // 如果函数体不做return返回值，即验证通过，控件正常处理业务
  console.log('当前变化的数据', current)
  console.log('已选择的数据', chooseList)
  if (chooseList && chooseList.length > 4) {
    return '最多可以选择4个节点'
  }
}
function openTree() {
  nextTreeRef.value.showTree = true
}
</script>
<style lang="scss" scoped>
.login_bg {
  position: absolute;
  width: 100%;
  height: 340rpx;
}
.login_title {
  position: relative;
  z-index: 2;
  width: 100%;
  height: 230rpx;
  line-height: 250rpx;
  text-align: center;
}
.footer {
  bottom: 10rpx;
  width: 100%;
  background-color: #fff;
}
.imgCont {
  position: relative;
  z-index: 2;
  height: 130rpx;
  background: #fff;
  border-top-left-radius: 36rpx;
  border-top-right-radius: 36rpx;
}
:deep(.wd-button.is-medium.is-round) {
  width: 100%;
  color: #fff !important;
  background-color: #029669 !important;
}
.inline-txt {
  display: inline-block;
  margin: 0 8px;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
  vertical-align: middle;
}
:deep(.group) {
  margin-top: 12px;
  border-radius: 36rpx;
}
:deep(.wd-img-cropper) {
  z-index: 100 !important;
}
:deep(.wd-img) {
  left: 50%;
  z-index: 100;
  transform: translateX(-50%);
}
:deep(.wd-input__placeholder) {
  color: #bfbfbf !important;
}
:deep(.wd-input.is-disabled .wd-input__inner) {
  color: #262626 !important;
}

:deep(.wd-checkbox.is-checked .wd-checkbox__shape) {
  background: #029669 !important;
  border-color: #029669 !important;
}
</style>
